package com.wxf.exceltoword.controller;

import com.alibaba.fastjson.JSON;
import com.wxf.exceltoword.config.Config;
import com.wxf.exceltoword.service.DataFilterService;
import com.wxf.exceltoword.util.DateUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wxf
 */
@Controller
public class IndexController {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private DataFilterService dataFilterService;
    @Autowired
    private Config config;

    /**
     * 根路径
     * @return
     */
    @GetMapping("")
    public @ResponseBody
    String home(){
        return "Start UP ..";
    }

    /**
     * 测试读取配置文件
     * @return
     */
    @GetMapping("/config")
    public @ResponseBody String config(){
        return "当前环境：" + config.getNowProfile();
    }

    /**
     * 页面测试
     * @return
     */
    @GetMapping("/index")
    public String index(ModelMap modelMap, @RequestParam String code){

        modelMap.put("code",code);
        modelMap.put("name","和讯");

        return "index";
    }
    
    /**
	 * 导入页面
	 * @param req
	 * @return
	 * @throws Exception
	 */
    @GetMapping("to_upload")
	public 	String toUpload(HttpServletRequest req) {
		return "upload_excel";
	}

    
    /**
	 * 上传图片
	 */
	@RequestMapping(value="upload_file",method=RequestMethod.POST,  produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("localFile") MultipartFile attachFile){

		Map<String, Object> jsonMap=new HashMap<String, Object>();
		
        //上传文件后缀名称
		String extendName = attachFile.getOriginalFilename().substring(attachFile.getOriginalFilename().lastIndexOf("."));
		//新文件名称
		String newFileName = UUID.randomUUID().toString() + extendName;

		try
		{
			//应用的真实路径
			String realContextPath = request.getSession().getServletContext().getRealPath("/");
 			String relativePath = "upload/" + DateUtils.getDate(new Date());
			// 新文件所属目录
 			File destFile = new File(realContextPath + relativePath);
 			
			
			if (!destFile.exists()){
				destFile.mkdirs();
			}
			
 			// 新文件
			File normalFile = new File(destFile, newFileName);
			attachFile.transferTo(normalFile);
			
			jsonMap.put("req_code", "T");
			jsonMap.put("req_mess", "文件上传成功");
			jsonMap.put("fileURL", normalFile);
			
			jsonMap.put("error", 0);
			jsonMap.put("url", normalFile);

			String docTemFilePath = "D:/exceltoword/docTem.doc";
			File docTemFile = new File(docTemFilePath);
			// 操作excel
			dataFilterService.importExcel(normalFile,docTemFile);
			

			log.info("上传成功，返回参数：{}", JSON.toJSONString(jsonMap));
		} catch (Exception e) {
			e.printStackTrace();
			jsonMap.put("req_code", "F");
			jsonMap.put("req_mess", "文件上传失败");
			
			jsonMap.put("error", 1);
			jsonMap.put("message", e.toString());
		}
        
        return jsonMap;
	}
   /* @PostMapping("/add")
    @ApiOperation(value="保存数据测试")
    public @ResponseBody Map<String,Object> add(@RequestBody Demo demo){
        Map<String,Object> map = new HashMap<>();
        log.info(" ** 接收到请求信息：{}", JSON.toJSONString(demo));
        demo.setId(UUID.randomUUID().toString().replaceAll("-",""));
        try {
            demoService.insert(demo);
            map.put("respCode","T");
        }catch (Exception e){
            map.put("respCode","T");
            e.printStackTrace();
        }
        return map;
    }*/
}
